<template>
  <div class="app-container customer-div">
    <div style="margin-top: 20px">
      <!--搜索-->
      <el-form :inline="true" :model="params" size="mini" label-width="130px">
        <el-form-item label="发货日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="params.shipDate"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select v-model="params.userId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户编号：">
          <el-input v-model="params.customerNumber"></el-input>
<!--          <el-select-->
<!--                  clearable-->
<!--                  v-model="params.customerId"-->
<!--                  filterable-->
<!--                  remote-->
<!--                  reserve-keyword-->
<!--                  placeholder="请输入关键词"-->
<!--                  :remote-method="remoteMethod"-->
<!--                  :loading="loading2">-->
<!--            <el-option-->
<!--                    v-for="item in customerList"-->
<!--                    :key="item.customerId"-->
<!--                    :label="item.customerName"-->
<!--                    :value="item.customerId">-->
<!--            </el-option>-->
<!--          </el-select>-->
        </el-form-item>
        <el-form-item>
          <el-button
                  @click="handleSearchList()"
                  type="primary">
            查询
          </el-button>
<!--          <el-button-->
<!--                  :loading="btnloading"-->
<!--                  @click="downloadExcel()"-->
<!--                  type="primary">-->
<!--            导出-->
<!--          </el-button>-->
<!--          <el-button-->
<!--                  :loading="btnloading2"-->
<!--                  @click="downloadExcel2()"-->
<!--                  type="primary">-->
<!--            成交客户导出-->
<!--          </el-button>-->
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="list"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
                prop="kingNumber"
                label="客户代码"
                align="center">
        </el-table-column>
        <el-table-column
                label="客户编号"
                align="center">
                <template slot-scope="scope">
                  <div>{{scope.row.customerNumber }}</div>
                  <!--是否有权限-->
                  <div v-if="scope.row.isShowCustomerName">{{scope.row.customerName}}</div>
                </template>
        </el-table-column>
        <el-table-column
                prop="goodsName"
                label="商品名称">
        </el-table-column>
        <el-table-column
                prop="shipDate"
                label="日期"
                align="center">
        </el-table-column>
        <el-table-column
                prop="shipNum"
                label="数量(吨)">
        </el-table-column>
        <el-table-column
                prop="userName"
                label="业务员"
                align="center">
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="params.pageNum"
        :page-size="params.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

  </div>
</template>

<script>
    import { getSaleDeliverList,getOrderUsersList,getCustomerOption} from '@/api/partner'
    import {hasOrderCustomers} from '@/api/company';
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    import XLSX from "xlsx-style"

    export default {
        name: "monthAnalysis",
        data(){
            return{
                roles:store.getters.roles ? store.getters.roles : [],
                params:{
                  pageNum:1,
                  pageSize:10,
                  shipDate:[],
                  userId:null,
                  customerId:null,
                  customerNumber:''
                },
                list:[],
                count:0,
                loading:false,
                userOptionList:[],
                customerList:[],
                loading2:false,
                btnloading:false,
                exData:{},
                btnloading2:false,
            }
        },
        computed: {
          ...mapGetters([
            'name',
            'mobile',
            'userId'
          ]),


        },
        created() {
          this.getListData();
          this.getUserOptionList();
        },
        filters: {
            formatTime(time) {
                let date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd')
            },
        },
        methods:{
          downloadExcel2(){
            this.btnloading2 = true;
            let params = {isExport : 1};
            hasOrderCustomers(params).then((res)=>{
              this.btnloading2 = false;
              require.ensure([], () => {
                const { export_json_to_excel } = require('sheet/Export2Excel');
                let tHeader = res.title;
                let filterVal = res.columns;
                let list = res.list;
                let data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, res.fileName);
              })
            }).catch(()=>{
              this.btnloading2 = false;
            })
          },
          //下载excle
          downloadExcel(){
            let params = JSON.parse(JSON.stringify(this.params));
            params.isExport = 1;
            this.btnloading = true;
            getSaleDeliverList(params).then((res)=>{
              this.btnloading = false;
              require.ensure([], () => {
                const { export_json_to_excel } = require('sheet/Export2Excel');
                const tHeader = res.title;
                const filterVal = res.columns;
                const list = res.list;
                const data = this.formatJson(filterVal, list);
                export_json_to_excel(tHeader, data, res.fileName);
              })
            }).catch(()=>{
              this.btnloading = false;
            })
          },

          //下载表格数据格式化
          formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
          },

          handleDownClick(){
            let data = JSON.parse(JSON.stringify(this.params));
            data.isExport=1;
            this.btnloading = true
            getSaleDeliverList(data).then((res)=>{
              this.btnloading = false;
              //表格标题
              var dataTitle = '销售分析';
              // 配置文件类型
              const wopts = { bookType: 'xlsx', bookSST: true, type: 'binary', cellStyles: true };
              this.exData = res;
              this.downloadExl(this.exData.list, wopts, dataTitle)
            }).catch(()=>{
              this.btnloading = false;
            })
          },
          downloadExl(json, type, dataTitle) {
            var tmpdata = json[0];
            json.unshift({});
            var keyMap = []; //获取keys
            for (var k in tmpdata) {
              keyMap.push(k);
              // json[0][k] = k;
            }
            var tmpdata = [];//用来保存转换好的json
            json.map((v, i) => {
              let data = keyMap.map((k, j) => {
                // console.log(k,this.getCharCol(j));
                return Object.assign({}, {
                  v: v[k],
                  position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i+1)
                });
              });
              return data;

            }).reduce((prev, next) => prev.concat(next)).forEach((v, i) => tmpdata[v.position] = {
              v: v.v
            });
            var outputPos = Object.keys(tmpdata); //设置区域,比如表格从A1到D10
            // tmpdata["A1"] = {v:dataTitle};
            // outputPos = ["A1"].concat(outputPos);
            // console.log("outputPos",outputPos);
            this.exData.colorRow.forEach((el)=>{
              tmpdata[el].s = { font: { sz: 12, bold: true, vertAlign:true ,color:{ rgb: "ffffff"}}, alignment:{ vertical:"center", horizontal:"center" }, fill: { bgColor: { rgb: "0058cf"}, fgColor: { rgb: "0058cf" } } };//<====设置xlsx单元格样式
            })
            tmpdata["!merges"] = this.exData.mergeRow;//<====合并单元格
            tmpdata["!cols"] = [
              {wpx: 200},
              {wpx: 200},
              {wpx: 200},
              {wpx: 200},
              {wpx: 200},
              {wpx: 200},
            ];//<====设置一列宽度

            var tmpWB = {
              SheetNames: ['mySheet'], //保存的表标题
              Sheets: {
                'mySheet': Object.assign({},
                        tmpdata, //内容
                        {
                          '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] //设置填充区域
                        }
                )
              }
            };
            var tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
                    { bookType: (type == undefined ? 'xlsx' : type.bookType), bookSST: false, type: 'binary' }//这里的数据是用来定义导出的格式类型
            ))], {
              type: ""
            });
            this.saveAs(tmpDown, dataTitle + '.' + (type.bookType == "biff2" ? "xls" : type.bookType));
          },
          // 下载功能
          saveAs(obj, fileName) {
            var tmpa = document.createElement("a");
            tmpa.download = fileName || "未命名";
            // 兼容ie
            if ("msSaveOrOpenBlob" in navigator) {
              window.navigator.msSaveOrOpenBlob(obj, fileName+ ".xlsx");
            } else {
              tmpa.href = URL.createObjectURL(obj);
            }
            tmpa.click();
            setTimeout(function() {
              URL.revokeObjectURL(obj);
            }, 100);
          },


          // 获取26个英文字母用来表示excel的列
          getCharCol(n) {
            let temCol = '',
                    s = '',
                    m = 0
            while (n > 0) {
              m = n % 26 + 1
              s = String.fromCharCode(m + 64) + s
              n = (n - m) / 26
            }
            return s
          },
          s2ab(s) {
            if (typeof ArrayBuffer !== 'undefined') {
              var buf = new ArrayBuffer(s.length);
              var view = new Uint8Array(buf);
              for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
              return buf;
            } else {
              var buf = new Array(s.length);
              for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
              return buf;
            }
          },
          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
              this.userOptionList = res;
            })
          },

          //获取客户列表
          remoteMethod(query) {
            if(query && query!= ''){
              this.loading2 = true;
              getCustomerOption({keywords:query}).then(response => {
                this.customerList = response;
                this.loading2 = false;
              }).catch(()=>{
                this.loading2 = false;
              });
            }
          },

          handleSearchList(){
                this.params.pageNum = 1;
                this.getListData();
            },

            handleSizeChange(val){
                this.params.pageNum = 1;
                this.params.pageSize = val;
                this.getListData();
            },
            handleCurrentChange(val){
                this.params.pageNum = val;
                this.getListData();
            },

            getListData(){
              this.loading = true;
              getSaleDeliverList(this.params).then((res)=>{
                this.list = res.list;
                this.count = res.count;
                this.loading = false;
              }).catch(()=>{
                this.loading = false;
              })
            },

        },
    }
</script>

<style scoped lang="scss">
  .avatar-uploader{
    margin-bottom:10px;
    display: inline-block;
    width:80px;
    height:80px;
    border:1px solid #DCDFE6;
    text-align: center;
    line-height: 80px;
  }
</style>
